package com.hzeport.bgs22emduty.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hzeport.bgs22emduty.config.SystemConfig;
import com.hzeport.bgs22emduty.config.login.UserInfoDetailVO;
import com.hzeport.bgs22emduty.dto.ScreenEmergencyPlanDTO;
import com.hzeport.bgs22emduty.entity.Appendix;
import com.hzeport.bgs22emduty.entity.ScreenDutyWork;
import com.hzeport.bgs22emduty.entity.ScreenStandard;
import com.hzeport.bgs22emduty.enums.DeleteFlagEnum;
import com.hzeport.bgs22emduty.outbound.AppendixRepository;
import com.hzeport.bgs22emduty.outbound.ScreenEmergencyPlanRepository;
import com.hzeport.bgs22emduty.vo.ScreenEmergencyPlan.ScreenEmergencyPlanSaveVO;
import com.hzeport.bgs22emduty.vo.ScreenEmergencyPlan.ScreenPlanSortVO;
import com.hzeport.bgs22emduty.vo.ScreenStandard.ScreenStandardsaveVO;
import com.hzeport.bgs22emduty.vo.file.FileVO;
import com.hzeport.bgs22emduty.common.base.BaseEntity;
import com.hzeport.bgs22emduty.common.base.BaseResult;
import com.hzeport.bgs22emduty.common.base.BaseServiceImpl;
import com.hzeport.bgs22emduty.entity.ScreenEmergencyPlan;
import com.hzeport.bgs22emduty.outbound.db.ScreenEmergencyPlanRepositoryImpl;
import com.hzeport.bgs22emduty.service.ScreenEmergencyPlanService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * ${comments}
 *
 * @author code generator
 * @date 2023-02-14 09:39:44
 */
@Service
@Slf4j
public class ScreenEmergencyPlanServiceImpl extends BaseServiceImpl<ScreenEmergencyPlanRepositoryImpl, ScreenEmergencyPlan> implements ScreenEmergencyPlanService {

    @Resource
    private ScreenEmergencyPlanRepository screenEmergencyPlanRepository;
    @Resource
    private SystemConfig systemConfig;
    @Resource
    private AppendixRepository appendixRepository;


    @Override
    public BaseResult<Page<ScreenEmergencyPlan>> list(ScreenEmergencyPlanDTO dto, UserInfoDetailVO userInfoDetailVO) {
        LambdaQueryWrapper<ScreenEmergencyPlan> queryWrapper=new LambdaQueryWrapper<>();
        if(!CollectionUtils.isEmpty(dto.getData())&&dto.getData().get(0)!=null){
            queryWrapper.ge(ScreenEmergencyPlan::getCreateTime, LocalDateTime.parse(dto.getData().get(0)+"T00:00:00"));
        }
        if(!CollectionUtils.isEmpty(dto.getData())&&dto.getData().get(1)!=null){
            queryWrapper.le(ScreenEmergencyPlan::getCreateTime, LocalDateTime.parse(dto.getData().get(1)+"T23:59:59"));
        }
        if(!StringUtils.isEmpty(dto.getTitle())){
            queryWrapper.like(ScreenEmergencyPlan::getTitle,dto.getTitle());
        }
        queryWrapper.eq(StringUtils.isNotBlank(userInfoDetailVO.getCustomscode()), ScreenEmergencyPlan::getCustomId,userInfoDetailVO.getCustomscode());
        queryWrapper.orderByAsc(ScreenEmergencyPlan::getSort).orderByAsc(BaseEntity::getCreateTime);
        Page<ScreenEmergencyPlan> page = new Page<>(dto.getPageNum(),dto.getPageSize());
        Page<ScreenEmergencyPlan> standardPage = screenEmergencyPlanRepository.page(page, queryWrapper);
        return BaseResult.ok(standardPage,"查询成功");
    }

    @Override
    public BaseResult delete(String id, UserInfoDetailVO userInfoDetailVO) {
        screenEmergencyPlanRepository.update(new LambdaUpdateWrapper<ScreenEmergencyPlan>()
                .eq(ScreenEmergencyPlan::getId,id)
                .set(ScreenEmergencyPlan::getDelFlag,DeleteFlagEnum.IS_DELETE.getValue())
                .set(ScreenEmergencyPlan::getUpdateBy,userInfoDetailVO.getUserId())
                .set(ScreenEmergencyPlan::getUpdateTime,LocalDateTime.now()));
        appendixRepository.remove(new LambdaQueryWrapper<Appendix>().eq(Appendix::getRelevanceId,id));
        return BaseResult.ok(null,"删除成功");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public BaseResult saveData(ScreenEmergencyPlanSaveVO screenEmergencyPlanSaveVO, UserInfoDetailVO userInfoDetailVO) throws Exception {
//        if (CollectionUtils.isEmpty(screenEmergencyPlanSaveVO.getFiles())){
//            throw new Exception("必须传递pdf文件！");
//        }
//        FileVO file=screenEmergencyPlanSaveVO.getFiles().get(0);
//        if (!file.getCurrentFileName().endsWith(".pdf")){
//            throw new Exception("文件后缀名必须为pdf！");
//        }
        ScreenEmergencyPlan screenEmergencyPlan = new ScreenEmergencyPlan();
        BeanUtils.copyProperties(screenEmergencyPlanSaveVO,screenEmergencyPlan);
        if(StringUtils.isEmpty(screenEmergencyPlanSaveVO.getId())){
            screenEmergencyPlan.setCustomId(userInfoDetailVO.getCustomscode());
            screenEmergencyPlan.setCustomName(userInfoDetailVO.getCustomsName());
            screenEmergencyPlan.setCreateBy(userInfoDetailVO.getUserId());
            screenEmergencyPlan.setCreateTime(LocalDateTime.now());
            screenEmergencyPlan.setUpdateBy(userInfoDetailVO.getUserId());
            screenEmergencyPlan.setUpdateTime(LocalDateTime.now());
            screenEmergencyPlan.setDelFlag(DeleteFlagEnum.NOT_DELETE.getValue());
            screenEmergencyPlanRepository.save(screenEmergencyPlan);
            List<FileVO> files = screenEmergencyPlanSaveVO.getFiles();
            files.forEach(fileVO -> {
                LambdaUpdateWrapper<Appendix> wrapper = new LambdaUpdateWrapper<>();
                wrapper.eq(Appendix::getId,fileVO.getId()).set(Appendix::getRelevanceId,screenEmergencyPlan.getId());
                appendixRepository.update(wrapper);
            });
        }else {
            if(StringUtils.isEmpty(screenEmergencyPlanSaveVO.getMainBody())){
                screenEmergencyPlan.setMainBody("");
            }
            ScreenEmergencyPlan byId = repository.getById(screenEmergencyPlanSaveVO.getId());
            if (byId != null){
                screenEmergencyPlan.setRecVersion(byId.getRecVersion());
            }
            screenEmergencyPlan.setCustomId(userInfoDetailVO.getCustomscode());
            screenEmergencyPlan.setCustomName(userInfoDetailVO.getCustomsName());
            screenEmergencyPlan.setUpdateBy(userInfoDetailVO.getUserId());
            screenEmergencyPlan.setUpdateTime(LocalDateTime.now());
            screenEmergencyPlan.setDelFlag(DeleteFlagEnum.NOT_DELETE.getValue());
            screenEmergencyPlanRepository.updateById(screenEmergencyPlan);

            List<FileVO> files = screenEmergencyPlanSaveVO.getFiles();
            List<Appendix> list = appendixRepository.list(new LambdaQueryWrapper<Appendix>().eq(Appendix::getRelevanceId,screenEmergencyPlan.getId()));
            if (CollectionUtils.isEmpty(list)) {
                if (!CollectionUtils.isEmpty(files)) {
                    files.forEach(s -> {
                        LambdaUpdateWrapper<Appendix> wrapper = new LambdaUpdateWrapper<>();
                        wrapper.eq(Appendix::getId,s.getId()).set(Appendix::getRelevanceId,screenEmergencyPlan.getId());
                        appendixRepository.update(wrapper);
                    });
                }
            }else {
                if (CollectionUtils.isEmpty(files)) {
                    if (!CollectionUtils.isEmpty(list)) {
                        appendixRepository.remove(new LambdaQueryWrapper<Appendix>().eq(Appendix::getRelevanceId, screenEmergencyPlan.getId()));
                    }
                }else {
                    List<String> collect = files.stream().map(FileVO::getId).collect(Collectors.toList());
                    List<String> collect3 = list.stream().map(Appendix::getId).collect(Collectors.toList());
                    List<String> collect1 = collect3.stream().filter(item -> !collect.contains(item)).collect(Collectors.toList());
                    appendixRepository.removeByIds(collect1);
                    List<String> collect2 = collect.stream().filter(item-> !collect3.contains(item)).collect(Collectors.toList());
                    collect2.forEach(s -> {
                        LambdaUpdateWrapper<Appendix> wrapper = new LambdaUpdateWrapper<>();
                        wrapper.eq(Appendix::getId,s).set(Appendix::getRelevanceId,screenEmergencyPlan.getId());
                        appendixRepository.update(wrapper);
                    });
                }
            }
        }
        return BaseResult.ok(screenEmergencyPlan,"保存成功");
    }

    @Override
    public BaseResult<ScreenEmergencyPlanSaveVO> detail(String id) {
        ScreenEmergencyPlan screenEmergencyPlan = screenEmergencyPlanRepository.getById(id);
        List<FileVO> fileVOS = appendixRepository.list(new LambdaQueryWrapper<Appendix>().eq(Appendix::getRelevanceId, id))
                .stream().map(appendix -> {
                    FileVO fileVO = new FileVO();
                    BeanUtils.copyProperties(appendix,fileVO);
                    return fileVO;
                }).collect(Collectors.toList());
        ScreenEmergencyPlanSaveVO screenEmergencyPlanSaveVO = new ScreenEmergencyPlanSaveVO();
        BeanUtils.copyProperties(screenEmergencyPlan,screenEmergencyPlanSaveVO);
        screenEmergencyPlanSaveVO.setFiles(fileVOS);
        return BaseResult.ok(screenEmergencyPlanSaveVO,"查看成功");
    }

    @Override
    public BaseResult saveSort(ScreenPlanSortVO screenPlanSortVO, UserInfoDetailVO userInfoDetailVO) {
        ScreenEmergencyPlan byId = screenEmergencyPlanRepository.getById(screenPlanSortVO.getId());
        ScreenEmergencyPlan screenEmergencyPlan = new ScreenEmergencyPlan();
        BeanUtils.copyProperties(byId,screenEmergencyPlan);
        screenEmergencyPlan.setSort(screenPlanSortVO.getSort());
        screenEmergencyPlan.setUpdateBy(userInfoDetailVO.getUserId());
        screenEmergencyPlan.setUpdateTime(LocalDateTime.now());
        screenEmergencyPlanRepository.updateById(screenEmergencyPlan);
        return  BaseResult.ok(screenEmergencyPlan,"成功");
    }


}
